package downloader

import (
	"os"
	"time"
)

// Clean 清理本地文件，id不为nil时清理指定ID的任务
// 否则检查所有任务的过期时间，过期的任务文件将被清除
func (cls *Downloader) Clean(id *string) {
	cls.mutex.RLock()
	defer cls.mutex.RUnlock()

	if nil != id {
		if task, ok := cls.tasks[*id]; ok {
			_ = os.RemoveAll(task.LocalFilepath)
			task.LocalFileRemoved = true
		}

		return
	}

	var now = time.Now()
	for _, task := range cls.tasks {
		if TaskStateComplete != task.State && TaskTargetTemporary != task.Target {
			continue
		}

		// 移除本地文件
		if now.Sub(task.EndTime) > task.Timeout {
			_ = os.RemoveAll(task.LocalFilepath)
			task.LocalFileRemoved = true
		}
	}
}
